/*
 * @Author: your name
 * @Date: 2021-03-04 21:57:34
 * @LastEditTime: 2021-03-07 14:22:03
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \longan\lib\usart.c
 */

#include "gd32vf103_gpio.h"
#include "gd32vf103_usart.h"
#include "rtthread.h"
int usart0_config(void)
{
  /* enable USART clock */
  rcu_periph_clock_enable(RCU_USART0);

#if defined USART0_REMAP
  /* enable GPIO clock */
  rcu_periph_clock_enable(RCU_GPIOB);
  rcu_periph_clock_enable(RCU_AF);
  /* USART0 remapping */
  gpio_pin_remap_config(GPIO_USART0_REMAP, ENABLE);
  /* connect port to USARTx_Tx */
  gpio_init(GPIOB, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_6);
  /* connect port to USARTx_Rx */
  gpio_init(GPIOB, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_7);
#else
  /* enable GPIO clock */
  rcu_periph_clock_enable(RCU_GPIOA);

  /* connect port to USARTx_Tx */
  gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_9);
  /* connect port to USARTx_Rx */
  gpio_init(GPIOA, GPIO_MODE_IN_FLOATING, GPIO_OSPEED_50MHZ, GPIO_PIN_10);
#endif

  /* USART configure */
  usart_deinit(USART0);
  usart_baudrate_set(USART0, 115200U);
  usart_word_length_set(USART0, USART_WL_8BIT);
  usart_stop_bit_set(USART0, USART_STB_1BIT);
  usart_parity_config(USART0, USART_PM_NONE);
  usart_hardware_flow_rts_config(USART0, USART_RTS_DISABLE);
  usart_hardware_flow_cts_config(USART0, USART_CTS_DISABLE);
  usart_receive_config(USART0, USART_RECEIVE_ENABLE);
  usart_transmit_config(USART0, USART_TRANSMIT_ENABLE);
  usart_enable(USART0);

  return 0;
}
INIT_BOARD_EXPORT(usart0_config);

/* retarget the C library printf function to the USART */
int _put_char(int ch)
{
  usart_data_transmit(USART0, (uint8_t)ch);
  while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET)
  {
  }

  return ch;
}

unsigned char _get_char(void)
{
  /* 等待接收到数据 */
  while (usart_flag_get(USART0, USART_FLAG_RBNE) == RESET)
  {
  }

  return (unsigned char)usart_data_receive(USART0);
}

void my_fputc(unsigned char ch)
{
  /* 写一个字节到USART0 */
  usart_data_transmit(USART0, (uint8_t)ch);
  /* 等待发送结束 */
  while (usart_flag_get(USART0, USART_FLAG_TBE) == RESET)
  {
  }
}

unsigned char my_fgetc(void)
{
  /* 等待接收到数据 */
  while (usart_flag_get(USART0, USART_FLAG_RBNE) == RESET)
  {
  }

  return (unsigned char)usart_data_receive(USART0);
}